package com.java.base.exercise.current;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author RenPu
 * @Date 2021/9/8 17:18
 * @Version 1.0
 * @Description: 测试来观察公平和非公平锁在获取锁时的区别，在测试用例中定义了内部
 * 类ReentrantLock2，该类主要公开了getQueuedThreads()方法，该方法返回正在等待获取锁的线
 * 程列表，由于列表是逆序输出，为了方便观察结果，将其进行反转
 **/
public class FairAndUnfairTest {

    private static Lock fairLock = new ReentrantLock2(true);
    private static Lock unfairLock = new ReentrantLock2(false);

    public void fair() {
        testLock(fairLock);
    }

    public void unfair() {
        testLock(unfairLock);
    }

    private void testLock(Lock lock) {
// 启动5个Job（略）
    }

    private static class Job extends Thread {
        private Lock lock;

        public Job(Lock lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
// 连续2次打印当前的Thread和等待队列中的Thread（略）
        }
    }

    private static class ReentrantLock2 extends ReentrantLock {
        public ReentrantLock2(boolean fair) {
            super(fair);
        }

        @Override
        public Collection<Thread> getQueuedThreads() {
            List<Thread> arrayList = new ArrayList<Thread>(super.
                    getQueuedThreads());
            Collections.reverse(arrayList);
            return arrayList;
        }
    }


}
